using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace JiebaNet.Analyser
{
    public class IdfLoader
    {
        internal string IdfFilePath { get; set; }
        internal IDictionary<string, double> IdfFreq { get; set; }
        internal double MedianIdf { get; set; }

        public IdfLoader(string idfPath = null, Stream stream = null)
        {
            IdfFilePath = string.Empty;
            IdfFreq = new Dictionary<string, double>();
            MedianIdf = 0.0;
            if (!string.IsNullOrWhiteSpace(idfPath))
            {
                SetNewPath(idfPath);
            }
            else if (stream != null)
            {
                SetByStream(stream);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="idfStream"></param>
        public void SetByStream(Stream idfStream)
        {
            using (StreamReader reader = new StreamReader(idfStream, Encoding.UTF8))
            {
                var lines = new List<string>();
                string line;
                while((line = reader.ReadLine()) != null)
                {
                    lines.Add(line);
                }
                LoadLines(lines);
            }
        }

        public void SetNewPath(string newIdfPath)
        {
            var idfPath = Path.GetFullPath(newIdfPath);
            if (IdfFilePath != idfPath)
            {
                IdfFilePath = idfPath;
                var lines = File.ReadAllLines(idfPath, Encoding.UTF8);
                LoadLines(lines);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="lines"></param>
        private void LoadLines(IEnumerable<string> lines)
        {
            IdfFreq = new Dictionary<string, double>();
            foreach (var line in lines)
            {
                var parts = line.Trim().Split(' ');
                var word = parts[0];
                var freq = double.Parse(parts[1]);
                IdfFreq[word] = freq;
            }
            MedianIdf = IdfFreq.Values.OrderBy(v => v).ToList()[IdfFreq.Count / 2];
        }
    }
}